package com.laputa.web.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.actions.EventDispatchAction;

import com.laputa.service.method.LoginService;
import com.laputa.service.model.MainFrameData;

public class LoginAction extends EventDispatchAction {

	private LoginService loginService;

	/*
	 * Generated Methods
	 */
	public void setLoginService(LoginService loginService) {
		this.loginService = loginService;
	}

	public ActionForward login(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		String actionPath = "";
		DynaActionForm toidentify = (DynaActionForm) form;
		String username = (String) toidentify.get("name");
		String userpass = (String) toidentify.get("password");
		if (loginService.validate(username, userpass)) {
			MainFrameData data = (MainFrameData) loginService.getmainFrameData(username);
			request.getSession().setAttribute("userData", data);
			request.setAttribute("userID", data.getId());
			actionPath = "success";
		} else {
			request.setAttribute("errorMsg", "登录失败");
			actionPath = "fail";
		}
		return mapping.findForward(actionPath);
	}

	public ActionForward register(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		return mapping.findForward("register");
	}
	
	public ActionForward home(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		MainFrameData data = (MainFrameData) loginService.getmainFrameData(
				((MainFrameData)request.getSession().getAttribute("userData")).getName());
		request.getSession().setAttribute("userData", data);
		return mapping.findForward("success");
	}

	public ActionForward logout(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		request.getSession().removeAttribute("userData");
		return mapping.findForward("logout");
	}
}
